package com.think.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.think.common.utils.DateUtils;
import com.think.entity.WebsiteNum;
import com.think.mapper.WebsiteNumMapper;
import com.think.service.IWebsiteNumService;
import com.think.vo.WebsiteNumVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author bridge
 * @Date 2021/10/16/13:55
 */
@Service
public class  WebsiteNumServiceImpl extends ServiceImpl<WebsiteNumMapper, WebsiteNum> implements IWebsiteNumService {

    @Override
    public int addWebsiteNum(WebsiteNum websiteNum) {
        if (websiteNum == null) {
            return 0;
        }

        QueryWrapper<WebsiteNum> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(websiteNum.getIp()), "ip", websiteNum.getIp());
        queryWrapper.eq("date_format(create_date, '%Y-%m-%d')",LocalDate.now()+"");
        WebsiteNum rstWebsite = this.baseMapper.selectOne(queryWrapper);
        if (rstWebsite != null) {
            rstWebsite.setPv(rstWebsite.getPv() + 1L);
            rstWebsite.setUpdateDate(new Date());
            return this.baseMapper.updateById(rstWebsite);
        }
        websiteNum.setUv(1L);
        websiteNum.setPv(1L);
        websiteNum.setCreateBy(-1);
        websiteNum.setCreateDate(new Date());
        websiteNum.setUpdateBy(-1);
        websiteNum.setUpdateDate(new Date());
        return this.baseMapper.insert(websiteNum);
    }

    @Override
    public List<WebsiteNumVO> queryWebsiteNum() {

        return this.baseMapper.queryWebsiteNum();
    }

    @Override
    public IPage<WebsiteNum> pageList(WebsiteNum websiteNum, int current, int size) {
        current = current > 0 ? current : 1;
        size = size > 0 ? size : 20;
        QueryWrapper<WebsiteNum> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(websiteNum.getIp()), "ip", websiteNum.getIp());
        Page<WebsiteNum> page = new Page<>(current, size);
        return this.baseMapper.selectPage(page, queryWrapper);
    }
}
